<template>
  <div class="yun-view">
    <div class="yun-xls-head">
      <div class="xls-file">
          <div class="file-name">文件名称：{{ fileInfo.fileName }}</div>
        <div class="xls-btn">
          <el-upload action="#" class="yun-upload" :before-upload="handleUpload" :show-file-list="false">
            <el-button type="primary">导入excel</el-button>
          </el-upload>
          <el-button type="primary" @click="handleExport">导出excel</el-button>
          <el-button type="primary">导出json</el-button>
          <el-button type="primary" @click="saveFile">保存</el-button>
          <el-button type="primary" @click="routeBack">返回</el-button>
        </div>
      </div>
      
      
      <div class="edit-users">
        <el-tag class="yun-tag" v-for="item in Ydata.userList" :key="item">{{ item }}</el-tag>
      </div>
    </div>
    <div class="luckysheet" id="lucky"></div>
  </div>
</template>
<script setup>
import {reactive,onMounted} from 'vue'
import { useRoute,useRouter } from "vue-router";
import { exportExcel } from "@/utils/exportJs";
import {xlsOnload,xlsAddOrUpload} from '@/api/onlineOffice.js'
import LuckyExcel from "luckyexcel";
import {useUserStore} from '@/store/userStore'
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()

const fileInfo = reactive({
  fileName:'',
  id:null
})
// 记录用户操作
const userOption = reactive({})
fileInfo.fileName = route.query.fileName || ""
fileInfo.id = route.query.id || null
const socket = new WebSocket(`ws://127.0.0.1:8000/file/${fileInfo.id}/`)
socket.onopen = ()=>{
  console.log('前端连接成功')
  let msg = {type:"open",user:userStore.userInfo.name,msg:`${userStore.userInfo.name}上线了`}
  socket.send(JSON.stringify(msg))
}
socket.onmessage = (msg)=>{
  console.log('前端接收到数据',msg)
  let data = JSON.parse(msg.data)
  Ydata.userList = data.userList || []
  for(let user in data.msg.userOption){
    userOption[user]=data.msg.userOption[user]
  }
  try{
    let sheetData = JSON.parse(data.msg.msg)
    sheetData.forEach(sheet=>{
      sheet.celldata.forEach(cell=>{
        console.log(cell)
        let celljson = JSON.parse(JSON.stringify(cell.v))
        console.log(celljson)
        luckysheet.setCellValue(cell.r, cell.c, celljson.v);
      })
    })
    uploadtip()
  }catch{

  }
 
}
socket.onclose = ()=>{
}
const fCellMousedown = (cell, position)=>{
    userOption[userStore.userInfo.id] = {
      left: position.start_c, //批注框左边距
      top: position.start_r>0?position.start_r-28:position.start_r+20, //批注框上边距
      id:userStore.userInfo.id,
      value: userStore.userInfo.name , //批准内容 
    }
    uploadtip()
    let msg = {type:"send",user:userStore.userInfo.name,userOption,msg:JSON.stringify(window.luckysheet.getAllSheets())}
    socket.send(JSON.stringify(msg))
}
const cellEditEvent = (value)=>{
  let cell = value[0]
  userOption[userStore.userInfo.id] = {
    left: cell.left, //批注框左边距
    top: cell.top>0?cell.top-28 :cell.top+20 , //批注框上边距
    id:userStore.userInfo.id,
    value: userStore.userInfo.name + "正在编辑", //批准内容 
  }
    uploadtip()
    let msg = {type:"send",user:userStore.userInfo.name,userOption,msg:JSON.stringify(window.luckysheet.getAllSheets())}
    socket.send(JSON.stringify(msg))
  }
const uploadtip=()=>{
  let showBox =  document.getElementById("luckysheet-cell-main")
  for(let user in userOption){
    let ed = userOption[user]
    let olddom = document.getElementById(`userid-${ed.id}`)
    if(olddom){
      showBox.removeChild(olddom)
    }
    let dom = document.createElement('div')
    dom.setAttribute('id',`userid-${ed.id}`)
    dom.setAttribute('style',`padding:2px 4px;color:#fff;padding:5px;border: 1px solid #f8f2f2;background-color:rgb(253 3 3);position:absolute;left:${ed.left}px;top:${ed.top}px;box-sizing:border-box;z-index:100;`)
    dom.innerHTML = ed.value
    showBox.appendChild(dom)
  }
}
const sheetData = reactive({
  options:{
    container: 'lucky',
    lang: 'zh',
    allowUpdate: false,
    enableAddRow:false,
    enableAddBackTop:false,
    showinfobar: false,
    data:null,
    hook: {
      cellMousedown: fCellMousedown,
      cellEditBefore: cellEditEvent
    },
  },
})
//在线用户
const Ydata =reactive({
  userList:['admin','wolf']
})

const initSheet = ()=>{
  window.luckysheet.create(sheetData.options);
}
onMounted(()=>{
  getFileInfo()
  initSheet()
})
const getFileInfo = async()=>{
  let res = await xlsOnload(fileInfo.id)
  if(res.code==200){
    sheetData.options.data= JSON.parse(res.data.fileContent)
    initSheet()
  }
}
const saveFile = async ()=>{
  let params = {
    id:fileInfo.id,
    name:fileInfo.fileName,
    fileContent: JSON.stringify(window.luckysheet.getAllSheets())
  }
  console.log(params)
  let res = await xlsAddOrUpload(params)
  if(res.code==200){
    ElMessage.success("保存成功")
  }
}


//上传文件并解析
const handleUpload = (file)=>{
  if (!file) return;
  let suffixArr = file.name.split("."),
    suffix = suffixArr[suffixArr.length - 1];
  if (suffix !== "xlsx") {
    ElMessage.error("目前只支持xlsx格式的文件");
    return;
  }
  //解析上传的文件
  LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile) => {
    console.log(file,exportJson)
        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
          ElMessage.error("解析文件失败")
        }
        window.luckysheet.destroy();
        sheetData.options.data = exportJson.sheets;
        initSheet();
  });
}
//导出xls
const handleExport = ()=>{
  exportExcel(window.luckysheet.getAllSheets(), fileInfo.fileName||"文档");
}
//返回
const routeBack = ()=>{
  router.go(-1)
}
</script>
<style lang="scss" scoped>
.yun-xls-head{
  width:100%;
  height:50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .xls-file{
    display: flex;
    align-items: center;
  }
  .xls-btn{
    margin-left:20px;
    display: flex;
    align-items: center;
    .yun-upload{
      margin-right:10px;
    }
  }
  .edit-users{
    max-width:40%;
    overflow-y:auto;
  }
  .yun-tag{
    margin-right:5px;
  }
}
.luckysheet{
  width:100%;
  height:calc(100% - 120px);
}
</style>